package file.day9_23;

public class SyncDemo {
    public static void main(String[] args) {
        Table table = new Table();

        Thread t1 = new Thread(){
            public void run(){
                while (true){
                    int bean = table.getBean();
                    Thread.yield();

                    System.out.println(getName()+":"+bean);
                }

            }
        };

        Thread t2 = new Thread(){
            public void run(){
                while (true){
                    int bean = table.getBean();
                    Thread.yield();

                    System.out.println(getName()+":"+bean);
                }


            }
        };

        t1.start();
        t2.start();

    }
}
class Table{
    private int beans = 20;
    public synchronized int getBean(){//当一个方法使用synchronized修饰后，这个方法称为同步方法(有先后顺序的排队)，
        // 多个线程不能同时执行该方法
        if(beans == 0){
            throw new RuntimeException("没有豆子");
        }
        Thread.yield();

        return beans--;
    }
}
